package controllers

import (
	"encoding/json"
	"onion/models"
	"onion/utils/crypt"
	"onion/utils/tool"

	"github.com/astaxie/beego/orm"
)

type AdminController struct {
	BaseController
}

type AdminParam struct {
	Username string `json:"username"`
	Password string `json:"password"`
}

type SetPassword struct {
	Username    string `json:"username"`
	Password    string `json:"password"`
	NewPassword string `json:"new"`
}

func (this *AdminController) Login() {
	var admin AdminParam
	var err error
	if err = json.Unmarshal(this.Ctx.Input.RequestBody, &admin); err == nil {
		o := orm.NewOrm()
		v := models.BxMenber{}
		v.Username = admin.Username
		if err = o.Read(&v, "username"); err != nil {
			this.ErrorJson(tool.ACCOUNTERR, "该账号不存在")
			return
		}
		if v.Password != crypt.MD5String(admin.Password+v.Salt) {
			this.ErrorJson(tool.ACCOUNTERR, "密码错误")
			return
		}
		v.Logtime = this.GetTimeString()
		v.Logip = this.GetIP()
		if _, err = o.Update(&v); err != nil {
			this.ErrorJson(tool.DBERROR, "登录失败")
			return
		}
		this.Success("登录成功")
		return
	}
	this.ErrorJson(tool.PARAMERR, "解析参数失败")
}

func (this *AdminController) Logout() {
	var admin AdminParam
	var err error
	if err = json.Unmarshal(this.Ctx.Input.RequestBody, &admin); err == nil {
		o := orm.NewOrm()
		v := models.BxMenber{}
		v.Username = admin.Username
		if err = o.Read(&v, "username"); err != nil {
			this.ErrorJson(tool.ACCOUNTERR, "账号错误")
			return
		}
		if v.Password != crypt.MD5String(admin.Password+v.Salt) {
			this.ErrorJson(tool.ACCOUNTERR, "密码错误")
			return
		}
		this.Success("退出登录成功")
	}
	this.ErrorJson(tool.PARAMERR, "解析参数失败")
}

func (this *AdminController) SetPWD() {
	var admin SetPassword
	var err error
	if err = json.Unmarshal(this.Ctx.Input.RequestBody, &admin); err == nil {
		o := orm.NewOrm()
		v := models.BxMenber{}
		v.Username = admin.Username
		if err = o.Read(&v, "username"); err != nil {
			this.ErrorJson(tool.ACCOUNTERR, "该账号不存在")
			return
		}
		if v.Password != crypt.MD5String(admin.Password+v.Salt) {
			this.ErrorJson(tool.ACCOUNTERR, "密码错误")
			return
		}
		v.Password = crypt.MD5String(admin.NewPassword + v.Salt)
		if _, err = o.Update(&v); err != nil {
			this.ErrorJson(tool.DBERROR, "修改密码出错")
			return
		}
		this.Success("修改密码成功", map[string]interface{}{
			"new": admin.NewPassword,
		})
	}
	this.ErrorJson(tool.PARAMERR, "解析参数失败")
}
